using FluentValidation;
using Zhaoxi.Zhihu.Core.QuestionAggregate.Entites;
using Zhaoxi.Zhihu.Core.QuestionAggregate.Specifications;
using Zhaoxi.Zhihu.SharedKerel.Messaging;
using Zhaoxi.Zhihu.SharedKerel.Repositoy;
using Zhaoxi.Zhihu.SharedKerel.Result;
using Zhaoxi.Zhihu.UseCases.Common.Attributes;
using Zhaoxi.Zhihu.UseCases.Common.Interface;

namespace Zhaoxi.Zhihu.UseCases.Questions.Command;

[Authorize]
public record DeleteQuestionCommand(int Id) : ICommand<IResult>;
public class DeleteQuestionCommandValidator : AbstractValidator<DeleteQuestionCommand>
{
    public DeleteQuestionCommandValidator()
    {
        RuleFor(c => c.Id).GreaterThan(0);
    }
}

public class DeleteQuestionCommandHandler (IRepository<Question> questions,
    IUser user): ICommandHandler<DeleteQuestionCommand, IResult>
{
    public async Task<IResult> Handle(DeleteQuestionCommand request, CancellationToken cancellationToken)
    {
       var spec=new QuestionWithAnswerByCreatedBy(user.Id!.Value,request.Id);
       var question=await questions.GetSingleOrDefaultAsync(spec,cancellationToken);
       if (question == null) return Result.NotFound("问题不存在");
       if (question.Answers.Count != 0) return Result.Failure("问题下有答案，不能删除");
       
       questions.Delete(question);
       
       await questions.SaveChangesAsync(cancellationToken);
       
       return Result.Success();
       
    }
}